package com.uenpay.im.ui.old.activity.shake;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.listener.OnHttpRequestTextListener;
import com.qiyunxin.android.http.net.HttpInvokeItem;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpRequestType;
import com.qiyunxin.android.http.net.HttpTextAsyncTask;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.listener.ShakeListener;
import com.qyx.android.weight.listener.ShakeListener.OnShakeListener;
import com.qyx.android.weight.utils.baidumap.IGetLocationListener;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.base.BaseActivity;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.weight.RoundImageView;

import java.io.IOException;

public class ShakeActivity extends BaseActivity {
	private ShakeListener mShakeListener = null;
	private Vibrator mVibrator;
	private String cust_id = "";
	private TextView nameTv, distanceTv, no_people_tv;
	private RoundImageView avatarIv;
	private ImageView sexIv;
	private LinearLayout loading_layout;
	private MediaPlayer BackgroundMediaPlayer;
	private String soundName = "";
	private String lLatitude, lLongitude;
	private boolean getData = false;
	private RelativeLayout userLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		IMApplication.getInstance().addActivity(this);
		setContentView(R.layout.activity_shake_layout);
		initView();
		initListener();
		backListener();
		getLoaction();
	}

	@Override
	protected  void initView() {
		TextView middleText = (TextView) findViewById(R.id.title_textview);
		middleText.setText(R.string.shake);
		nameTv = (TextView) findViewById(R.id.name_tv);
		no_people_tv = (TextView) findViewById(R.id.no_people_tv);
		distanceTv = (TextView) findViewById(R.id.distance_tv);
		sexIv = (ImageView) findViewById(R.id.sex_iv);
		avatarIv = (RoundImageView) findViewById(R.id.avatar_iv);
		loading_layout = (LinearLayout) findViewById(R.id.loading_layout);
		userLayout = (RelativeLayout) findViewById(R.id.user_layout);
	}

	@Override
	protected  void initListener() {
		findViewById(R.id.user_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (!TextUtils.isEmpty(cust_id)) {
							ActivityHandle.startUserDetailActivity(ShakeActivity.this, cust_id);
						}
					}
				});
	}

	private void initShake() {
		if (mVibrator == null) {
			mVibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
		}
		mShakeListener = new ShakeListener(this);
		mShakeListener.setOnShakeListener(new OnShakeListener() {

			@Override
			public void onShake() {
				startShakeAnim();// �?始震动动�?
				startVibrator();// �?始震�?
				mShakeListener.stop();// 取消监听�?
				playSound("shake_sound_male.mp3", false);// 播放�?始声�?
				userLayout.setVisibility(View.GONE);
				no_people_tv.setVisibility(View.GONE);
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						// 播放结束声音
						playSound("shake_match.mp3", false);
						// 停止震动
						mVibrator.cancel();
						if (TextUtils.isEmpty(lLatitude)
								|| TextUtils.isEmpty(lLongitude)) {
							finish();
						} else {
							getShakePeople();
						}
					}
				}, 2000);
			}
		});
	}

	private void startVibrator() {
		mVibrator.vibrate(new long[] { 500, 200, 500, 200 }, -1);
	}

	private void startShakeAnim() {
		// shake_top
		Animation ani_shake_top = AnimationUtils.loadAnimation(this,
				R.anim.up_shaketop);
		((ImageView) findViewById(R.id.viewpager_shake_top))
				.startAnimation(ani_shake_top);
		// shake_bottom
		Animation ani_shake_bottom = AnimationUtils.loadAnimation(this,
				R.anim.down_shakebottom);
		((ImageView) findViewById(R.id.viewpager_shake_bottom))
				.startAnimation(ani_shake_bottom);
	}

	private void getShakePeople() {
		if (getData) {
			return;
		}
		getData = true;
		loading_layout.setVisibility(View.VISIBLE);
		GetShakePeopleInvokItem item = new GetShakePeopleInvokItem(lLongitude,
				lLatitude);
		HttpRequestAsyncTaskQueue
				.getInstance()
				.AddTask(
						new HttpTextAsyncTask(item)
								.SetRequestType(HttpRequestType.SERVER_ONLY),
						new OnHttpRequestTextListener() {

							@Override
							public void OnFail(boolean isCache, String reason) {
								getData = false;
								myHandler.sendEmptyMessage(1);
							}

							@Override
							public void OnProgress(long total_bytes,
									long downloaded_bytes) {
							}

							@Override
							public void OnSuccess(HttpInvokeItem item,
									boolean isCache, String cacheFilePath) {
								getData = false;
								myHandler.sendEmptyMessage(1);
								GetShakePeopleInvokItem.GetShakePeopleInvokItemResult result = ((GetShakePeopleInvokItem) item)
										.getOutput();
								if (result != null) {
									if (result.status == HttpInvokeResultCode.RESULT_OK) {
										cust_id = result.custid;
										nameTv.setText(result.nickname);
										distanceTv.setText(result.distance);
										avatarIv.SetUrl(APIConfiguration
												.getAvatarUrlNormal(
														result.custid,
														PacketType.PERSONAL));
										if (result.sex == 1) {
											sexIv.setImageResource(R.drawable.icon_man);
										} else {
											sexIv.setImageResource(R.drawable.icon_woman);
										}
										userLayout.setVisibility(View.VISIBLE);
									} else {
										no_people_tv
												.setVisibility(View.VISIBLE);
										userLayout.setVisibility(View.GONE);
									}

									loading_layout.setVisibility(View.GONE);
								} else {

								}
							}
						});

	}


	private Handler myHandler = new Handler(new Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 1) {
				if (loading_layout != null) {
					loading_layout.setVisibility(View.GONE);
					if (mShakeListener != null)
						mShakeListener.start();// 注册监听
				}
			}

			return false;
		}
	});

	private void playSound(String name, boolean isLoop) {
		if (BackgroundMediaPlayer == null) {
			BackgroundMediaPlayer = new MediaPlayer();
		}
		if (BackgroundMediaPlayer != null) {
			if (name.equalsIgnoreCase(soundName)) {
				if (!BackgroundMediaPlayer.isPlaying()) {
					BackgroundMediaPlayer.start();
				}
				return;
			}
			BackgroundMediaPlayer.stop();
			BackgroundMediaPlayer.reset();
			BackgroundMediaPlayer.setLooping(isLoop);

			AssetManager am = getAssets();
			try {
				AssetFileDescriptor afd = am.openFd(name);
				BackgroundMediaPlayer.setDataSource(afd.getFileDescriptor(),
						afd.getStartOffset(), afd.getLength());
				BackgroundMediaPlayer.prepare();
				BackgroundMediaPlayer.start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		soundName = name;
	}

	@Override
	protected void onResume() {
		initShake();
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mShakeListener != null) {
			mShakeListener.stop();
			mShakeListener = null;
		}
		if (BackgroundMediaPlayer != null && BackgroundMediaPlayer.isPlaying()) {
			BackgroundMediaPlayer.pause();
		}
	}

	private void getLoaction() {
		IMApplication.getInstance().GetBaiduLoacationUtil()
				.getGoogleLoaction(new IGetLocationListener() {

					@Override
					public void onSuccess(BDLocation location) {
						lLatitude = location.getLatitude() + "";
						lLongitude = location.getLongitude() + "";
					}

					@Override
					public void onFail() {
						finish();
					}
				});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		IMApplication.getInstance().removeActivity(this);
		if (mShakeListener != null) {
			mShakeListener.stop();
			mShakeListener = null;
		}
	}

}